<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="100px"
        >
            <el-form-item label="招聘计划名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入招聘计划名称"
                    clearable
                />
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >查询</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <TableCard>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['back:plan:add']"
                        >添加招聘计划</el-button
                    >
                </el-col>
            </el-row>

            <el-table
                :border="Global.tableShowBorder"
                v-loading="loading"
                :data="planList"
                @selection-change="handleSelectionChange"
            >
                <el-table-column
                    type="index"
                    label="序号"
                    width="55"
                    align="center"
                />
                <el-table-column
                    label="招聘计划名称"
                    align="center"
                    prop="name"
                />
                <el-table-column
                    label="创建时间"
                    align="center"
                    prop="createTime"
                />
                <el-table-column
                    label="更新时间"
                    align="center"
                    prop="updateTime"
                />
                <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handleLook(scope.row)"
                            >查看</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['back:plan:edit']"
                            >修改</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-if="
                                $store.getters.allDefectObj['HR-WEB-113'] == 1
                            "
                            >删除</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-position"
                            @click="goToPosition(scope.row)"
                            >招聘职位管理</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                v-show="total > 10"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </TableCard>

        <!-- 添加或修改招聘计划对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="1000px"
            :rules="look ? '' : rules"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="80px"
                >
                    <el-form-item
                        label="名称"
                        prop="name"
                        :rules="
                            look
                                ? []
                                : $store.getters.allDefectObj['HR-WEB-115'] == 0
                                ? [
                                      {
                                          required: true,
                                          message: '名称不能为空',
                                          trigger: 'blur',
                                      },
                                  ]
                                : [
                                      {
                                          required: true,
                                          message: '名称不能为空',
                                          trigger: 'blur',
                                      },
                                      {
                                          max: 64,
                                          message: '长度不能超过 64 个字符',
                                          trigger: 'blur',
                                      },
                                  ]
                        "
                    >
                        <el-input
                            v-model="form.name"
                            placeholder="请输入名称"
                            :disabled="look"
                        />
                    </el-form-item>
                    <el-form-item label="内容" :prop="look ? '' : 'content'">
                        <editor
                            v-model="form.content"
                            :min-height="192"
                            :disabled="look"
                        />
                    </el-form-item>
                    <el-form-item label="上传附件" prop="fileUrl">
                        <file-upload2
                            v-model="form.fileUrl"
                            :fileSize="5"
                            :fileType="
                                $store.getters.allDefectObj['HR-WEB-116'] == 0
                                    ? ['doc', 'docx']
                                    : ['doc', 'docx', 'xlsx', 'xls']
                            "
                            :limit="10"
                            :disabled="look"
                        />
                    </el-form-item>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" v-if="!look" @click="submitForm"
                    >保 存</el-button
                >
                <el-button v-if="!look" @click="cancel">取 消</el-button>
                <el-button v-if="look" @click="cancel">返 回</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listPlan,
    getPlan,
    delPlan,
    addPlan,
    updatePlan,
} from "@/api/hrm/plan";
import fileUpload2 from "./fileUpload.vue";

export default {
    name: "Plan",
    data() {
        var checkName = (rule, value, callback) => {
            if (this.containsNameEqualTo(value)) {
                callback(new Error("名称已存在，请修改名称"));
            } else {
                callback();
            }
        };
        var contentMinLength = (rule, value, callback) => {
            if (this.countRemainingChars(value) == 0) {
                callback(new Error("内容不能为空"));
            } else {
                callback();
            }
        };
        var contentMaxLength = (rule, value, callback) => {
            if (this.countRemainingChars(value) > 5000) {
                callback(new Error("长度不能超过 5000 个字符"));
            } else {
                callback();
            }
        };
        return {
            look: false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 招聘计划表格数据
            planList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                orderByColumn: "createTime",
                isAsc: "descending",
                name: null,
                content: null,
                fileUrl: null,
            },
            // 表单参数
            form: { name: null },
            // 表单校验
            rules: {
                name: [
                    // {
                    //     validator: checkName,
                    //     message: "名称已存在，请修改名称",
                    //     trigger: "blur",
                    // },
                ],
                content: [
                    {
                        validator: contentMaxLength,
                        message: "长度不能超过 5000 个字符",
                        trigger: "blur",
                    },
                    {
                        validator: contentMinLength,
                        message: "内容不能为空",
                        trigger: "blur",
                    },
                    {
                        required: true,
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    components: { fileUpload2 },
    created() {
        this.getList();
    },
    methods: {
        nameMaxLength(rule, value, callback) {
            if (value && value.length > 64) {
                callback(new Error("长度不能超过 64 个字符"));
            } else {
                callback();
            }
        },
        containsNameEqualTo(value) {
            for (let i = 0; i < this.planList.length; i++) {
                if (this.planList[i].name === value) {
                    return true;
                }
            }
            return false;
        },
        countRemainingChars(str) {
            var cleanedStr = str.replace(/<[^>]*>/g, "");
            // 返回处理后的字符串长度
            return cleanedStr.length;
        },
        /** 查询招聘计划列表 */
        getList() {
            this.loading = true;
            listPlan(this.queryParams).then((response) => {
                this.planList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                content: null,
                fileUrl: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
            };
            this.resetForm("form");
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.look = false;
            this.reset();
            this.open = true;
            this.title = "添加招聘计划";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.look = false;
            this.reset();
            const id = row.id || this.ids;
            getPlan(id).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "修改招聘计划";
            });
        },
        handleLook(row) {
            this.look = true;
            this.reset();
            const id = row.id || this.ids;
            getPlan(id).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "查看招聘计划";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updatePlan(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addPlan(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm("确认要删除此条记录吗？")
                .then(function () {
                    return delPlan(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "back/plan/export",
                {
                    ...this.queryParams,
                },
                `plan_${new Date().getTime()}.xlsx`
            );
        },
        /** 跳转到岗位需求页面 */
        goToPosition(row) {
            this.$router.push({
                path: "/position",
                query: {
                    planId: row.id,
                    planName: row.name,
                },
            });
        },
    },
};
</script>
